<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request.js'

export default {
  name: 'Reports',
  setup() {
    const reports = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)

    const getReports = async (page = 1) => {
      try {
        const response = await request.get('/report/page', {
          params: {
            page: page,
            size: pageSize.value
          }
        })
        if (response.code === 1) {
          reports.value = response.data.list.map(report => ({
            ...report,
            id: report.id
          }))
          total.value = response.data.total
          currentPage.value = page
        } else {
          console.error(response.msg || '获取举报列表失败')
        }
      } catch (error) {
        console.error('服务异常')
      }
    }

    const formatStatus = (row, column, cellValue) => {
      return cellValue === 1 ? '未处理' : '已处理';
    }

    const handleViewDetail = async (report) => {
      try {
        const response = await request.get(`/report/${report.id}`)
        if (response.code === 1) {
          const reportDetails = response.data
          const isProcessed = report.status === 2

          const buttons = isProcessed
            ? [
                {
                  text: '返回',
                  onClick: () => ElMessage.info('操作已取消')
                }
              ]
            : [
                {
                  text: '审核通过',
                  type: 'primary',
                  onClick: async () => {
                    try {
                      const response = await request.put('/report', { id: report.id, flag: 1, commentId: reportDetails.commentId })
                      if (response.code === 1) {
                        ElMessage.success('审核通过成功')
                        getReports(currentPage.value)
                      } else {
                        ElMessage.error(response.msg || '审核通过失败')
                      }
                    } catch (error) {
                      ElMessage.error('服务异常')
                    }
                  }
                },
                {
                  text: '审核不通过',
                  onClick: async () => {
                    try {
                      const response = await request.put('/report', { id: report.id, flag: 2 })
                      if (response.code === 1) {
                        ElMessage.success('审核不通过成功')
                        getReports(currentPage.value)
                      } else {
                        ElMessage.error(response.msg || '审核不通过失败')
                      }
                    } catch (error) {
                      ElMessage.error('服务异常')
                    }
                  }
                }
              ]

          ElMessageBox.alert(
            `<div>
              <p><strong>被举报评论:</strong> ${reportDetails.comment}</p>
              <p><strong>举报原因:</strong> ${reportDetails.reason}</p>
            </div>`,
            '举报详细信息',
            {
              dangerouslyUseHTMLString: true,
              showCancelButton: !isProcessed,
              confirmButtonText: isProcessed ? '返回' : '审核通过',
              cancelButtonText: isProcessed ? null : '审核不通过',
              customClass: 'custom-message-box',
              closeOnClickModal: false,
              callback: (action) => {
                if (action === 'confirm' && !isProcessed) {
                  buttons[0].onClick()
                } else if (action === 'cancel' && !isProcessed) {
                  buttons[1].onClick()
                } else {
                  buttons[0].onClick()
                }
              }
            }
          )
        } else {
          ElMessage.error(response.msg || '获取举报详细信息失败')
        }
      } catch (error) {
        ElMessage.error('服务异常')
      }
    }

    onMounted(() => {
      getReports()
    })

    return {
      reports,
      currentPage,
      pageSize,
      total,
      getReports,
      handleViewDetail,
      formatStatus
    }
  }
}
</script>

<template>
  <div class="reports-container">
    <el-table :data="reports" style="width: 100%">
      <el-table-column prop="id" label="序号" width="100"></el-table-column>
      <el-table-column prop="userId" label="举报人（已加密）" width="180"></el-table-column>
      <el-table-column prop="reason" label="举报原因"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="formatStatus"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="handleViewDetail(scope.row)">查看详细</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @current-change="getReports"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<style scoped>
.reports-container {
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.custom-message-box .el-message-box__btns .el-button--primary {
  background-color: red;
  border-color: red;
}
</style>